package com.ruoyi.business.modbus.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.business.modbus.monitor.NetworkStabilityMonitor;

/**
 * 网络稳定性监控控制器
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@RestController
@RequestMapping("/business/modbus/network")
public class NetworkStabilityController extends BaseController
{
    @Autowired
    private NetworkStabilityMonitor networkStabilityMonitor;

    /**
     * 获取设备网络稳定性状态
     */
    @PreAuthorize("@ss.hasPermi('business:modbus:network:query')")
    @GetMapping("/stability/{deviceSN}")
    public AjaxResult getNetworkStability(@PathVariable String deviceSN)
    {
        NetworkStabilityMonitor.NetworkStabilityResult result = networkStabilityMonitor.isNetworkStable(deviceSN);
        
        Map<String, Object> response = Map.of(
            "deviceSN", deviceSN,
            "isStable", result.isStable(),
            "reason", result.getReason(),
            "qualityLevel", networkStabilityMonitor.getNetworkQualityLevel(deviceSN)
        );
        
        return AjaxResult.success("获取网络稳定性状态完成", response);
    }

    /**
     * 获取设备详细网络统计信息
     */
    @PreAuthorize("@ss.hasPermi('business:modbus:network:query')")
    @GetMapping("/stats/{deviceSN}")
    public AjaxResult getDeviceNetworkStats(@PathVariable String deviceSN)
    {
        Map<String, Object> stats = networkStabilityMonitor.getDeviceNetworkStats(deviceSN);
        return AjaxResult.success("获取设备网络统计信息完成", stats);
    }

    /**
     * 获取所有设备网络概览
     */
    @PreAuthorize("@ss.hasPermi('business:modbus:network:query')")
    @GetMapping("/overview")
    public AjaxResult getAllDevicesNetworkOverview()
    {
        Map<String, Object> overview = networkStabilityMonitor.getAllDevicesNetworkOverview();
        return AjaxResult.success("获取网络概览完成", overview);
    }

    /**
     * 获取网络质量等级
     */
    @PreAuthorize("@ss.hasPermi('business:modbus:network:query')")
    @GetMapping("/quality/{deviceSN}")
    public AjaxResult getNetworkQuality(@PathVariable String deviceSN)
    {
        String qualityLevel = networkStabilityMonitor.getNetworkQualityLevel(deviceSN);
        
        Map<String, Object> response = Map.of(
            "deviceSN", deviceSN,
            "qualityLevel", qualityLevel
        );
        
        return AjaxResult.success("获取网络质量等级完成", response);
    }

    /**
     * 清除指定设备的监控数据
     */
    @PreAuthorize("@ss.hasPermi('business:modbus:network:manage')")
    @DeleteMapping("/stats/{deviceSN}")
    public AjaxResult clearDeviceStats(@PathVariable String deviceSN)
    {
        networkStabilityMonitor.clearDeviceStats(deviceSN);
        return AjaxResult.success("清除设备监控数据完成");
    }

    /**
     * 清除所有设备的监控数据
     */
    @PreAuthorize("@ss.hasPermi('business:modbus:network:manage')")
    @DeleteMapping("/stats")
    public AjaxResult clearAllStats()
    {
        networkStabilityMonitor.clearAllStats();
        return AjaxResult.success("清除所有监控数据完成");
    }

    /**
     * 获取网络监控配置信息
     */
    @PreAuthorize("@ss.hasPermi('business:modbus:network:query')")
    @GetMapping("/config")
    public AjaxResult getMonitorConfig()
    {
        Map<String, Object> config = Map.of(
            "stableSuccessRate", "90%",
            "stableAvgResponseTime", "1000ms",
            "stableNoFailureTime", "5分钟",
            "minSamples", 10,
            "maxResponseSamples", 100,
            "description", "网络稳定性监控配置参数"
        );
        
        return AjaxResult.success("获取监控配置完成", config);
    }

    /**
     * 手动记录连接尝试（用于测试）
     */
    @PreAuthorize("@ss.hasPermi('business:modbus:network:manage')")
    @PostMapping("/record")
    public AjaxResult recordConnectionAttempt(@RequestBody Map<String, Object> params)
    {
        String deviceSN = params.get("deviceSN").toString();
        boolean success = Boolean.parseBoolean(params.get("success").toString());
        long responseTime = Long.parseLong(params.get("responseTime").toString());
        
        networkStabilityMonitor.recordConnectionAttempt(deviceSN, success, responseTime);
        
        return AjaxResult.success("记录连接尝试完成");
    }

    /**
     * 批量获取多个设备的网络状态
     */
    @PreAuthorize("@ss.hasPermi('business:modbus:network:query')")
    @PostMapping("/batch-stats")
    public AjaxResult getBatchDeviceStats(@RequestBody Map<String, Object> params)
    {
        @SuppressWarnings("unchecked")
        java.util.List<String> deviceSNs = (java.util.List<String>) params.get("deviceSNs");
        
        Map<String, Object> batchStats = new java.util.HashMap<>();
        
        for (String deviceSN : deviceSNs) {
            NetworkStabilityMonitor.NetworkStabilityResult result = networkStabilityMonitor.isNetworkStable(deviceSN);
            Map<String, Object> deviceInfo = Map.of(
                "isStable", result.isStable(),
                "reason", result.getReason(),
                "qualityLevel", networkStabilityMonitor.getNetworkQualityLevel(deviceSN),
                "stats", networkStabilityMonitor.getDeviceNetworkStats(deviceSN)
            );
            batchStats.put(deviceSN, deviceInfo);
        }
        
        return AjaxResult.success("批量获取设备网络状态完成", batchStats);
    }
}
